package fourfaith.com.ff_sl21_app.fragment;

import android.annotation.SuppressLint;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.nineoldandroids.view.ViewHelper;

import java.util.List;
import java.util.Map;

import fourfaith.com.ff_sl21_app.DeviceActivity;
import fourfaith.com.ff_sl21_app.R;
import fourfaith.com.ff_sl21_app.utils.ItemAnimation;


public class DeviceListFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener{
    private View view;

    private List<Map<String, Object>> datas;
    private MyAdapter listAdapter;

    private LinearLayout progressBar, listLayout, dataError,dataEmpty;

    private RecyclerView recyclerView;
    private SwipeRefreshLayout swipeRefreshLayout;
    private LinearLayoutManager mLayoutManager;
    private LinearLayout footLoad_layout;
    private int dimensionPixelSize = 0;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_device_list, null);
        dimensionPixelSize = this.getResources().getDimensionPixelSize(R.dimen.bottom_item_height);

        initView();

        return view;
    }

    /**
     * 数据加载失败显示错误页面
     */
    public void showErrorPage() {
        progressBar.setVisibility(View.GONE);
        listLayout.setVisibility(View.GONE);
        dataError.setVisibility(View.VISIBLE);
        dataEmpty.setVisibility(View.GONE);
    }

    /**
     * 数据加载中页面
     */
    public void showLoadingPage() {

        progressBar.setVisibility(View.VISIBLE);
        dataError.setVisibility(View.GONE);
        listLayout.setVisibility(View.GONE);
        dataEmpty.setVisibility(View.GONE);
    }

    /**
     * 数据页面
     */
    public void showDataPage() {

        progressBar.setVisibility(View.GONE);
        dataError.setVisibility(View.GONE);
        listLayout.setVisibility(View.VISIBLE);
        dataEmpty.setVisibility(View.GONE);
    }
    /**
     * 空数据页面
     */
    public void showEmptyPage() {

        progressBar.setVisibility(View.GONE);
        dataError.setVisibility(View.GONE);
        listLayout.setVisibility(View.GONE);
        dataEmpty.setVisibility(View.VISIBLE);
    }

    /**
     * 初始化布局
     */
    @SuppressLint({ "InlinedApi", "InflateParams" })
    private void initView() {

        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
        mLayoutManager = new LinearLayoutManager(getActivity());
        listAdapter = new MyAdapter();
        recyclerView.setLayoutManager(mLayoutManager);

        recyclerView.setAdapter(listAdapter);

        // 添加滑动监听
        recyclerView.addOnScrollListener(mOnScrollListener);

        //下拉刷新
        swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipeRefreshLayout);
        // 设置刷新时动画的颜色，可以设置4个
        swipeRefreshLayout.setColorSchemeResources(R.color.blue);

        swipeRefreshLayout.setOnRefreshListener(this);

        progressBar = (LinearLayout) view.findViewById(R.id.progressBar);
        listLayout = (LinearLayout) view.findViewById(R.id.listLayout);
        dataError = (LinearLayout) view.findViewById(R.id.dataError);
        dataEmpty = (LinearLayout) view.findViewById(R.id.dataEmpty);

    }

    public void finishRefreshing() {

        swipeRefreshLayout.setRefreshing(false);
        if(footLoad_layout!=null) footLoad_layout.setVisibility(View.GONE);
    }


    /**
     * 初始化数据
     */
    public void initData() {

        datas = DeviceActivity.dataList;

        listAdapter.notifyDataSetChanged();

        if(datas==null || datas.size()==0){
            showEmptyPage();
        }else{
            showDataPage();
        }

    }

    // RecyclerView的滑动监听事件
    private RecyclerView.OnScrollListener mOnScrollListener = new RecyclerView.OnScrollListener()
    {

        private int lastVisibleItem;

        // 滑动状态改变
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState)
        {
            super.onScrollStateChanged(recyclerView, newState);
            /**
             * scrollState有三种状态，分别是SCROLL_STATE_IDLE、SCROLL_STATE_TOUCH_SCROLL、SCROLL_STATE_FLING
             * SCROLL_STATE_IDLE是当屏幕停止滚动时
             * SCROLL_STATE_TOUCH_SCROLL是当用户在以触屏方式滚动屏幕并且手指仍然还在屏幕上时
             * SCROLL_STATE_FLING是当用户由于之前划动屏幕并抬起手指，屏幕产生惯性滑动时
             */
            if ( newState == RecyclerView.SCROLL_STATE_IDLE
                    && lastVisibleItem + 1 == listAdapter.getItemCount()
                    && listAdapter.isShowFooter())
            {

                footLoad_layout = (LinearLayout) view.findViewById(R.id.load_layout);
                footLoad_layout.setVisibility(View.VISIBLE);
                // 加载更多
                DeviceActivity.getDeviceRequest();
            }
        }

        // 滑动位置
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy)
        {
            super.onScrolled(recyclerView, dx, dy);
            // 给lastVisibleItem赋值
            // findLastVisibleItemPosition()是返回最后一个item的位置
            lastVisibleItem = mLayoutManager.findLastVisibleItemPosition();
        }

    };

    public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {


        // 设置底部布局
        private static final int TYPE_FOOTER = 0;
        // 设置默认布局
        private static final int TYPE_DEFAULT = 1;

        // 判断是不是最后一个item，默认是true
        private boolean mShowFooter = true;

        // 设置不同的item
        @Override
        public int getItemViewType(int position)
        {
            // 判断当前位置+1是不是等于数据总数（因为数组从0开始计数），是的就加载底部布局刷新，不是就加载默认布局
            if (position + 1 == getItemCount())
            {
                return TYPE_FOOTER;
            } else
            {
                return TYPE_DEFAULT;
            }
        }


        // 设置布局（相当于设置convertView）
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
        {

            if (viewType == TYPE_DEFAULT)
            {
                View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_device_list_item, parent, false);

                DefaultViewHolder vh = new DefaultViewHolder(v);
                v.setTag(vh);
                return vh;
            } else
            {
                // 实例化布局
                View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_footer, null);
                // 代码实现加载布局
                view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT));

                return new FooterViewHolder(view);
            }
        }

        // 在布局中加载数据（绑定数据）
        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position)
        {
            // 用来在运行时指出对象是某一个对象
            if (holder instanceof DefaultViewHolder)
            {
                Map<String,Object> item = datas.get(position);
                if (item == null)
                {
                    return;
                }

                //数据填充

                ((DefaultViewHolder) holder).deviceStatus.setImageResource((Integer) datas.get(position).get("deviceStatus"));
                ((DefaultViewHolder) holder).deviceName.setText((String) datas.get(position).get("deviceName"));
                ((DefaultViewHolder) holder).deviceCode.setText((String) datas.get(position).get("deviceCode"));
                ((DefaultViewHolder) holder).deviceTime.setText((String) datas.get(position).get("deviceTime"));
                ((DefaultViewHolder) holder).deviceAddress.setText((String) datas.get(position).get("deviceAddress"));

                ((DefaultViewHolder) holder).deviceModel.setText((String) datas.get(position).get("deviceModel"));
                ((DefaultViewHolder) holder).devicePhone.setText((String) datas.get(position).get("devicePhone"));
                ((DefaultViewHolder) holder).deviceCoords.setText((String) datas.get(position).get("deviceCoord"));

                ((DefaultViewHolder) holder).deviceDetail.setTag(position);
                ((DefaultViewHolder) holder).itemTitle.setTag(position);

                Object obj = datas.get(position).get("isOpen");
                boolean isOpen = false;
                if(obj!=null) isOpen = (boolean)datas.get(position).get("isOpen");

                if(isOpen)
                {
                    ((DefaultViewHolder) holder).detailText.setText("收起详情");
                    ViewHelper.setRotation(((DefaultViewHolder) holder).detailImg, 180f);
                    ((DefaultViewHolder) holder).deviceDetailLayout.getLayoutParams().height = dimensionPixelSize;
                    ((DefaultViewHolder) holder).deviceDetailLayout.setVisibility(View.VISIBLE);
                }else{
                    ((DefaultViewHolder) holder).detailText.setText("展开详情");
                    ViewHelper.setRotation(((DefaultViewHolder) holder).detailImg, 0f);
                    ((DefaultViewHolder) holder).deviceDetailLayout.getLayoutParams().height = 0;
                    ((DefaultViewHolder) holder).deviceDetailLayout.setVisibility(View.GONE);
                }
                ((DefaultViewHolder) holder).deviceDetail.setTag(position);

                ((DefaultViewHolder) holder).itemTitle.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        DeviceActivity.mTabPager.setCurrentItem(0);
                        int position = (Integer) v.getTag();
                        Map<String, Object> item = datas.get(position);

                        DeviceActivity.mapFragment.jumpAndShowInfo((String) item.get("deviceCode"));
                    }
                });

                ((DefaultViewHolder) holder).deviceDetail.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int position = (Integer) v.getTag();
                        Map<String, Object> item = datas.get(position);

                        Object obj = item.get("isOpen");
                        boolean isOpen = false;
                        if(obj!=null) isOpen = (boolean)item.get("isOpen");
                        item.put("isOpen", !isOpen);

                        ViewGroup itemView = (ViewGroup) v.getParent();
                        DefaultViewHolder songViewHolder = (DefaultViewHolder) itemView.getTag();

                        ItemAnimation.rotateSwitcherIcon(songViewHolder.detailImg, item, 180);
                        if(!isOpen) {
                            songViewHolder.detailText.setText("收起详情");
                            ItemAnimation.show(songViewHolder.deviceDetailLayout,dimensionPixelSize);
                        }
                        else{
                            ItemAnimation.hide(songViewHolder.deviceDetailLayout,dimensionPixelSize);
                            songViewHolder.detailText.setText("展开详情");
                        }
                    }
                });



            }
        }

        // 获取数据数目
        @Override
        public int getItemCount()
        {
            // 判断是不是显示底部，是就返回1，不是返回0
            int begin = mShowFooter? 1 : 0;
            // 没有数据的时候，直接返回begin
            if (datas == null)
            {
                return begin;
            }
            // 因为底部布局要占一个位置，所以总数目要+1
            return datas.size() + begin;
        }


        // 设置是否显示底部加载提示（将值传递给全局变量）
        public void isShowFooter(boolean showFooter)
        {
            this.mShowFooter = showFooter;
        }

        // 判断是否显示底部，数据来自全局变量
        public boolean isShowFooter()
        {
            return this.mShowFooter;
        }


        // 底部布局的ViewHolder
        public class FooterViewHolder extends RecyclerView.ViewHolder
        {
            public FooterViewHolder(View view)
            {
                super(view);
            }
        }

        // 默认布局的ViewHolder
        public class DefaultViewHolder extends RecyclerView.ViewHolder
        {

            public ImageView deviceStatus,imageView,detailImg;
            public TextView deviceName,deviceCode,deviceTime,deviceAddress,detailText;
            public TextView deviceModel,devicePhone,deviceCoords;
            public LinearLayout deviceDetail,deviceDetailLayout;
            public RelativeLayout itemTitle;

            public DefaultViewHolder(View itemView)
            {
                super(itemView);

                itemTitle= (RelativeLayout) itemView.findViewById(R.id.itemTitle);
                deviceStatus= (ImageView) itemView.findViewById(R.id.deviceStatus);
                imageView = (ImageView) itemView.findViewById(R.id.imageView);
                deviceName = (TextView) itemView.findViewById(R.id.deviceName);
                deviceCode = (TextView) itemView.findViewById(R.id.deviceCode);
                deviceTime = (TextView) itemView.findViewById(R.id.deviceTime);
                deviceAddress = (TextView) itemView.findViewById(R.id.deviceAddress);
                deviceDetail = (LinearLayout) itemView.findViewById(R.id.deviceDetail);
                deviceDetailLayout = (LinearLayout) itemView.findViewById(R.id.deviceDetailLayout);
                detailText = (TextView) itemView.findViewById(R.id.detailText);
                detailImg = (ImageView) itemView.findViewById(R.id.detailImg);

                deviceModel = (TextView) itemView.findViewById(R.id.deviceModel);
                devicePhone = (TextView) itemView.findViewById(R.id.devicePhone);
                deviceCoords = (TextView) itemView.findViewById(R.id.deviceCoord);

            }
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

    // 设置下拉刷新
    @Override
    public void onRefresh()
    {
        DeviceActivity.cleanData();
        datas.clear();
        listAdapter.notifyDataSetChanged();
        DeviceActivity.getDeviceRequest();
    }
}
